package web.controller;

import java.net.MalformedURLException;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import web.form.SearchForm;
import web.validator.SearchValidator;
import service.configuration.IConfiguration;

/**
 * <b>SearchController  </b>
 * <p>SearchController controle les requêtes pour la recherche d'une fiche.</p>
 * 
 */
@Controller
public class SearchController {
	
	/**
     * Repr&eacute;sente le service de configuration
     */
	@Resource
	private IConfiguration config;
	
	/**
     * Repr&eacute;sente le service de gestion de fiches
     */
	@Resource
	private SearchValidator searchValidator;


	/**
     * Controlleur qui renvoi la page de recherche
     */
	@RequestMapping(value = "/search.htm", method = RequestMethod.GET)
	public String handleRequest(HttpSession session, ModelMap model)  {
		SearchForm search = new SearchForm();
		
		model.addAttribute("sheetTypes", config.getSheetLabelByType());
	    model.addAttribute("searchForm", search);
	   
	    return "search";
	}
	
	/**
     * Controlleur qui recoi une requête de recherche et fait une redirection vers la page de fiche demandée
     */
	@RequestMapping(value = "/search.htm", method = RequestMethod.POST)
	public String onSubmitSearch(@RequestHeader("Referer") String referer, HttpSession session, @ModelAttribute("searchForm") SearchForm form,
								BindingResult result, ModelMap model) throws MalformedURLException {
		
		searchValidator.validate(form, result);
		
		
		if(result.hasErrors()) {
			model.addAttribute("sheetTypes", config.getSheetLabelByType());
			return "search";
		} else {
			URIParser uri = new URIParser("sheet.htm");
			uri.setParameter("code",form.getSheetCode());
			uri.setParameter("type",form.getSheetType());
			return "redirect:"+uri.getUrl();
		}
	}
}